<template>
  <div class="add-subject-cont">
    <h1>添加题目</h1>
    <n-divider />
    <n-space vertical>
      <n-form
        ref="subjectForm"
        :model="subjectModel"
        :rules="subjectRules"
        :label-width="100"
        size="large"
        label-placement="left"
      >
        <n-form-item label="题目类型：" path="subjectType">
          <n-radio-group
            v-model:value="subjectModel.subjectType"
            name="left-size"
          >
            <n-radio-button :value="1"> 单选题 </n-radio-button>
            <n-radio-button :value="0"> 判断题 </n-radio-button>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="题目：" path="title">
          <n-input
            v-model:value="subjectModel.title"
            type="textarea"
            placeholder="请输入题目内容"
          />
        </n-form-item>
        <n-form-item label="题目图片：" path="subjectImage">
          <FileUpload
            :uploadUrl="uploadUrl"
            :fileList="subjectModel.subjectImage"
            @update:fileList="val => (subjectModel.subjectImage = val)"
          />
        </n-form-item>
        <n-form-item label="选项：">
          <n-space vertical>
            <template
              v-for="(option, index) in subjectModel.options"
              :key="index"
            >
              <n-grid :cols="12" :x-gap="12">
                <n-form-item-gi
                  :span="3"
                  :label="`选项${index + 1}`"
                  label-width="auto"
                >
                  <n-radio-group
                    v-model:value="option.optionType"
                    name="left-size"
                  >
                    <n-radio-button :value="1"> 文字 </n-radio-button>
                    <n-radio-button :value="0"> 图片 </n-radio-button>
                  </n-radio-group>
                </n-form-item-gi>
                <n-form-item-gi v-if="option.optionType === 1" :span="5">
                  <n-input
                    v-model:value="option.optionText"
                    type="textarea"
                    placeholder="请输入选项"
                  />
                </n-form-item-gi>
                <n-form-item-gi v-else :span="5">
                  <FileUpload
                    :uploadUrl="uploadUrl"
                    :fileList="option.optionImage"
                    @update:fileList="val => (option.optionImage = val)"
                  />
                </n-form-item-gi>
                <n-form-item-gi :span="2">
                  <n-checkbox v-model:checked="option.isCorrect">
                    正确答案
                  </n-checkbox>
                </n-form-item-gi>

                <n-form-item-gi :span="2">
                  <n-space>
                    <n-button
                      v-show="subjectModel.options.length > 1"
                      strong
                      secondary
                      circle
                      type="error"
                      @click="subjectModel.options.splice(index, 1)"
                    >
                      <template #icon>
                        <n-icon><RemoveRound /></n-icon>
                      </template>
                    </n-button>
                    <n-button
                      strong
                      secondary
                      circle
                      type="success"
                      @click="addOption"
                    >
                      <template #icon>
                        <n-icon><AddFilled /></n-icon>
                      </template>
                    </n-button>
                  </n-space>
                </n-form-item-gi>
              </n-grid>
            </template>
          </n-space>
        </n-form-item>
        <n-form-item label="答案解析：" path="analysisText">
          <n-input
            v-model:value="subjectModel.analysisText"
            type="textarea"
            placeholder="请在此输入答案解析"
          />
        </n-form-item>
        <n-form-item label="解析视频：" path="analysisVideo">
          <FileUpload
            :uploadUrl="uploadUrl"
            :fileList="subjectModel.analysisVideo"
            accept="video/*"
            @update:fileList="val => (subjectModel.analysisVideo = val)"
          />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" @click="submitForm">提交</n-button>
        </n-form-item>
      </n-form>
    </n-space>
  </div>
</template>

<script setup>
import { AddFilled, RemoveRound } from '@vicons/material'
import { ref } from 'vue'
import { useMessage } from 'naive-ui'
import FileUpload from '@/components/FileUpload.vue'

const message = useMessage()

const uploadUrl = ref('http://localhost:3000/upload')

const subjectForm = ref(null)

const subjectModel = ref({
  subjectType: 1,
  title: '',
  subjectImage: [],
  options: [
    {
      optionType: 1,
      optionText: '',
      optionImage: [],
      isCorrect: false
    }
  ],
  analysisText: '',
  analysisVideo: []
})
const subjectModelClone = JSON.parse(JSON.stringify(subjectModel.value))
const subjectRules = ref({
  // title: [{ required: true, message: '请输入题目', trigger: 'blur' }]
})

const addOption = () => {
  subjectModel.value.options.push({
    optionType: 1,
    optionText: '',
    optionImage: [],
    isCorrect: false
  })
}

const submitForm = event => {
  event.preventDefault()
  subjectForm.value?.validate(valid => {
    console.log('valid', valid)
    if (!valid) {
      console.log('submit!!')
      postSubject()
      return true
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

const postSubject = async () => {
  const subjectData = JSON.parse(JSON.stringify(subjectModel.value))
  subjectData.options.map(
    option => (option.optionImage = option.optionImage?.[0]?.url ?? '')
  )
  subjectData.subjectImage = subjectData.subjectImage?.[0]?.url ?? ''
  subjectData.analysisVideo = subjectData.analysisVideo?.[0]?.url ?? ''

  const res = await fetch('http://localhost:3000/subjects', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(subjectData)
  })
  const data = await res.json()
  console.log(data)
  if (data.code === 200 || data.code === 201) {
    console.log('添加成功')
    message.success('添加成功')
    subjectModel.value = JSON.parse(JSON.stringify(subjectModelClone))
  } else {
    console.log('添加失败')
    message.error('添加失败')
  }
}
</script>

<style scoped>
.add-subject-cont {
  width: 900px;
  margin: 40px auto 0;
  padding: 26px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
}
</style>
